import { request } from "../utils/request";
/**
 * 封装预下单方法
 */
export function wxJSAPIPayOrder(data) {
  return new Promise(res => {
    request('/wxPayController/wxJSAPIPayOrder', 'POST', data,{
      "Content-Type": "application/json"
    })
    .then(resolve=>{
      if (resolve.success) {
        let payParams = resolve.data
        let nonceStr = payParams.nonceStr
        let paySign = payParams.paySign
        let prePayId = 'prepay_id='+payParams.prePayId
        let signType = payParams.signType
        let timeStamp = payParams.timeStamp
        wx.requestPayment({
          timeStamp: timeStamp, //时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间
          nonceStr: nonceStr, //随机字符串，长度为32个字符以下
          package: prePayId, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
          signType: signType,
          paySign: paySign, //签名，具体见微信支付文档
          success(res) {
            wx.showToast({
              title: '支付成功',
            })
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'error',
            })
          },
          complete(complete) {
            res(complete)
            console.log(complete);
          }
        })
      }else{
        wx.showToast({
          title: resolve.errorMessage,
          icon: 'error',
        })
        res(false)
      }
    })
  })
}

/**
 * 生成订单后的 支付接口
 */
export function getPrepayIdByTradeOrderId(data) {
  return new Promise(res => {
    request('/wxPayController/getPrepayIdByTradeOrderId', 'POST', data,{
      "Content-Type": "application/json"
    })
    .then(resolve=>{
      if (resolve.success) {
        let payParams = resolve.data
        let nonceStr = payParams.nonceStr
        let paySign = payParams.paySign
        let prePayId = 'prepay_id='+payParams.prePayId
        let signType = payParams.signType
        let timeStamp = payParams.timeStamp
        wx.requestPayment({
          timeStamp: timeStamp, //时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数，即当前的时间
          nonceStr: nonceStr, //随机字符串，长度为32个字符以下
          package: prePayId, //统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=***
          signType: signType,
          paySign: paySign, //签名，具体见微信支付文档
          success(res) {
            wx.showToast({
              title: '支付成功',
            })
          },
          fail(res) {
            console.error("微信支付之后了，原因如下：")
            console.error(res)
            wx.showToast({
              title: '支付失败',
              icon: 'error',
            })
          },
          complete(complete) {
            res(complete)
            console.log(complete);
          }
        })
      }else{
        wx.showToast({
          title: resolve.errorMessage,
          icon: 'error',
        })
        res(false)
      }
    })
  })
}
